//
//  PMSettingRateViewModel.m
//  Manager
//
//  Created by lvzhao on 2020/8/1.
//  Copyright © 2020 吕VV. All rights reserved.
//

#import "PMSettingRateViewModel.h"
@interface  PMSettingRateViewModel()

@property (nonatomic,assign) NSInteger pageIndex;

@end
@implementation PMSettingRateViewModel

- (void)setIndex:(NSInteger)index{
    _index = index;
    switch (index) {
        case 0:
            [self createUnAuthTable];
            break;
        case 1:
            [self createAuthable];
            break;
        default:
            break;
    }
}


//创建表格
- (void)createUnAuthTable{
    
    [self dataModel];
    /// top数据
    self.dataModel.topLeftDataModel = [[LZTableRightSubDataModel alloc] init];
    self.dataModel.topLeftDataModel.titleString = @"通道";
    self.dataModel.topLeftDataModel.sortStatus = 0;
    
    NSArray *titles = @[@"代码",@"费率",@"结算周期",@"付款下限",@"付款上限",@"是否迭代通道"];
    NSArray *itemWidthArray = @[@(100),@(80),@(100),@(100),@(100),@(120)];


    NSMutableArray *topSubDataArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < titles.count; i++) {
        LZTableRightSubDataModel *subDataModel = [[LZTableRightSubDataModel alloc]init];
        subDataModel.titleString = titles[i];
        subDataModel.itemHeight = self.dataModel.rowHeight;
        [topSubDataArray addObject:subDataModel];
    }
    self.dataModel.leftWidth = 100;
    [self.dataModel.topDataModel.classNames addObjectsFromArray:@[@"PMCustomSortCell"]];
    self.dataModel.topDataModel.setDataMethodName = @"setModelObject:";
    self.dataModel.topDataModel.itemModelArray = topSubDataArray;
    self.dataModel.topDataModel.columnWidthArray = itemWidthArray;
    self.dataModel.totalItemWidth = [[itemWidthArray valueForKeyPath:@"@sum.floatValue"] integerValue];

}


//创建表格
- (void)createAuthable{
    
    [self dataModel];
    
    /// top数据
    self.dataModel.topLeftDataModel = [[LZTableRightSubDataModel alloc] init];
    self.dataModel.topLeftDataModel.titleString = @"通道";
    self.dataModel.topLeftDataModel.sortStatus = 0;

    
    NSArray *titles = @[@"代码",@"费率",@"结算周期",@"付款下限",@"付款上限",@"权重",@"状态"];
    NSArray *itemWidthArray = @[@(100),@(80),@(100),@(100),@(100),@(80),@(80)];

    NSMutableArray *topSubDataArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < titles.count; i++) {
        LZTableRightSubDataModel *subDataModel = [[LZTableRightSubDataModel alloc]init];
        subDataModel.titleString = titles[i];
        subDataModel.itemHeight = self.dataModel.rowHeight;
        [topSubDataArray addObject:subDataModel];
    }
    self.dataModel.leftWidth = 100;
    [self.dataModel.topDataModel.classNames addObjectsFromArray:@[@"PMCustomSortCell"]];
    self.dataModel.topDataModel.setDataMethodName = @"setModelObject:";
    self.dataModel.topDataModel.itemModelArray = topSubDataArray;
    self.dataModel.topDataModel.columnWidthArray = itemWidthArray;
    self.dataModel.totalItemWidth = [[itemWidthArray valueForKeyPath:@"@sum.floatValue"] integerValue];

}
/** 未授权*/
- (void)getUnauthChannel:(BOOL)isFrist{

    if(isFrist){
        self.pageIndex = 1;
        self.dataModel.leftDataArray = @[];
        self.dataModel.dataArray = @[];
        [self.dataArray removeAllObjects];
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.pageIndex),
                                                                                    @"size":kPageSize,
                                                                                    @"status":@"ENABLE",
                                                                                    @"not_in_merchant_id":self.merchantModel.modelid}];
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kGetPageChannel params:params success:^(id  _Nullable responseObject) {
        @strongify(self);
        NSDictionary *pageDictionary = responseObject[@"page"];
        NSArray *dataArray = pageDictionary[@"list"];
        NSMutableArray * leftTableDataArray = [[NSMutableArray alloc]init];
        NSMutableArray * rowDataArray = [[NSMutableArray alloc]init];
        
        for (int i = 0; i < dataArray.count; i++){
            PMAuthorizedModel *dealModel = [PMAuthorizedModel modelWithJSON:dataArray[i]];
            [self.dataArray addObject:dealModel];
            // 左侧列表数据
            LZTableLeftDataModel * model = [[LZTableLeftDataModel alloc]init];
            model.titleString = dealModel.channel_name;
            [leftTableDataArray addObject:model];

            //右侧列表数据
            LZTableRightDataModel *rightDataModel = [[LZTableRightDataModel alloc]init];
            rightDataModel.itemHeight = self.dataModel.rowHeight;

            ///右侧数据源
            NSMutableArray * rightItemArray = [[NSMutableArray alloc]init];

            NSArray *detail = @[dealModel.channel_key?:@"",
                                dealModel.merchant_rate?:@"",
                                dealModel.settle_period?:@"",
                                dealModel.single_min?:@"",
                                dealModel.single_max?:@"",
                                dealModel.is_transfer?:@""];
            for ( int j = 0; j < detail.count; j++) {
                LZTableRightSubDataModel *itemModel = [[LZTableRightSubDataModel alloc]init];
                itemModel.titleString = detail[j];
                itemModel.itemHeight = self.dataModel.rowHeight;
                [rightItemArray addObject:itemModel];
            }
            rightDataModel.columnWidthArray = self.dataModel.topDataModel.columnWidthArray;
            rightDataModel.itemModelArray = rightItemArray;
            [rowDataArray addObject:rightDataModel];

            rightDataModel.setDataMethodName = @"setModelObject:";
            [rightDataModel.classNames addObjectsFromArray:@[@"PMCustomPayCell"]];
        }
        
        NSMutableArray *mutableLeftDataArray = [[NSMutableArray alloc] initWithArray:self.dataModel.leftDataArray];
        NSMutableArray *mutableRowDataArray = [[NSMutableArray alloc] initWithArray:self.dataModel.dataArray];

        [mutableLeftDataArray addObjectsFromArray:leftTableDataArray];
        [mutableRowDataArray addObjectsFromArray:rowDataArray];

        self.dataModel.leftDataArray = mutableLeftDataArray;
        self.dataModel.dataArray = mutableRowDataArray;
        ///回调
        if(dataArray.count < [kPageSize intValue]){
            [self.reloadSubject sendNext:@(0)];

        } else {
            self.pageIndex ++;
            [self.reloadSubject sendNext:@(1)];
        }
    } failure:^(NSError * _Nullable error) {
            @strongify(self);
          [self.reloadSubject sendNext:@(1)];
    }];
}


///授权开通
- (void)getOpenChannel:(NSDictionary *)dataDictionary{
    
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kOpenChannelToMerchant params:dataDictionary success:^(id  _Nullable responseObject) {
        if([responseObject[kResultStatus] isEqualToString:kCode]){
            showLoadingTitle(@"成功", nil);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
               @strongify(self);
               [self getUnauthChannel:YES];
           });
       }
   } failure:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];
}


///获取授权通道
- (void)getAuthChannel:(BOOL)isFrist{
    
    if(isFrist){
        self.pageIndex = 1;
        self.dataModel.leftDataArray = @[];
        self.dataModel.dataArray = @[];
        [self.dataArray removeAllObjects];
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@(self.pageIndex),
                                                                                    @"size":kPageSize,
                                                                                    @"merchant_id":self.merchantModel.modelid}];
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kGetMerchantChannel params:params success:^(id  _Nullable responseObject) {
        @strongify(self);
        NSDictionary *mchannelsDictionary = responseObject[@"mchannels"];
        NSArray *dataArray = mchannelsDictionary[@"list"];
        NSMutableArray * leftTableDataArray = [[NSMutableArray alloc]init];
        NSMutableArray * rowDataArray = [[NSMutableArray alloc]init];
        if(isFrist){
            self.pageIndex = 1;
            [self.dataArray removeAllObjects];
        }
        for (int i = 0; i < dataArray.count; i++){
            PMAuthorizedModel *dealModel = [PMAuthorizedModel modelWithJSON:dataArray[i]];
            [self.dataArray addObject:dealModel];
            // 左侧列表数据
            LZTableLeftDataModel * model = [[LZTableLeftDataModel alloc]init];
            model.titleString = dealModel.channel_name;
            [leftTableDataArray addObject:model];

            //右侧列表数据
            LZTableRightDataModel *rightDataModel = [[LZTableRightDataModel alloc]init];
            rightDataModel.itemHeight = self.dataModel.rowHeight;

            ///右侧数据源
            NSMutableArray * rightItemArray = [[NSMutableArray alloc]init];

            NSArray *detail = @[dealModel.channel_key?:@"",
                                dealModel.settle_rate?:@"",
                                dealModel.settle_period?:@"",
                                dealModel.single_min?:@"",
                                dealModel.single_max?:@"",
                                dealModel.custom_weight?:@"",
                                dealModel.status?:@""];
            for ( int j = 0; j < detail.count; j++) {
                LZTableRightSubDataModel *itemModel = [[LZTableRightSubDataModel alloc]init];
                itemModel.titleString = detail[j];
                itemModel.itemHeight = self.dataModel.rowHeight;
                
                if([itemModel.titleString isEqualToString:@"启用"]
                   ||[itemModel.titleString isEqualToString:@"关闭"]){
                    itemModel.textColor = UIColor.redColor;
                }

                [rightItemArray addObject:itemModel];
            }
            rightDataModel.columnWidthArray = self.dataModel.topDataModel.columnWidthArray;
            rightDataModel.itemModelArray = rightItemArray;
            [rowDataArray addObject:rightDataModel];

            rightDataModel.setDataMethodName = @"setModelObject:";
            [rightDataModel.classNames addObjectsFromArray:@[@"PMCustomPayCell"]];
        }
        
        NSMutableArray *mutableLeftDataArray = [[NSMutableArray alloc] initWithArray:self.dataModel.leftDataArray];
        NSMutableArray *mutableRowDataArray = [[NSMutableArray alloc] initWithArray:self.dataModel.dataArray];

        [mutableLeftDataArray addObjectsFromArray:leftTableDataArray];
        [mutableRowDataArray addObjectsFromArray:rowDataArray];

        self.dataModel.leftDataArray = mutableLeftDataArray;
        self.dataModel.dataArray = mutableRowDataArray;
        ///回调
        if(dataArray.count < [kPageSize intValue]){
            [self.reloadSubject sendNext:@(0)];

        } else {
            self.pageIndex ++;
            [self.reloadSubject sendNext:@(1)];
        }
    } failure:^(NSError * _Nullable error) {
            @strongify(self);
          [self.reloadSubject sendNext:@(1)];
    }];
}


///更新状态费率
- (void)updateMerchantChannelStatus:(NSDictionary *)dictionary{
    
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kUpdateMerchantChannelStatus params:dictionary success:^(id  _Nullable responseObject) {
        if([responseObject[kResultStatus] isEqualToString:kCode]){
            showDelayedDismissTitle(@"成功", nil);
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self);
                [self getAuthChannel:YES];
            });
            
        }
    } failure:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];
    
}

///删除费率
- (void)deleteMerchantChannel:(NSDictionary *)dictionary{
    
    @weakify(self);
    [LZNetworkingManager lz_request:@"post" url:kDeleteMerchantChannel params:dictionary success:^(id  _Nullable responseObject) {
        if([responseObject[kResultStatus] isEqualToString:kCode]){
            showDelayedDismissTitle(@"删除成功", nil);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self);
                [self getAuthChannel:YES];
            });
        }
    } failure:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];
}

///保存费率
- (void)saveMerchantChannel:(NSDictionary *)dictionary{
    
    @weakify(self);
   [LZNetworkingManager lz_request:@"post" url:kSaveMerchantChannel params:dictionary success:^(id  _Nullable responseObject) {
       if([responseObject[kResultStatus] isEqualToString:kCode]){
           showDelayedDismissTitle(@"保存成功", nil);
           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
               @strongify(self);
               [self getAuthChannel:YES];
           });
       }
   } failure:^(NSError * _Nullable error) {} isLoading:YES isFailTip:YES];
    
}

- (LZTableDataModel *)dataModel{
    if(!_dataModel){
        _dataModel = [[LZTableDataModel alloc] init];
        _dataModel.leftDataArray = @[];
        _dataModel.dataArray = @[];
    }
    return _dataModel;
}

- (NSMutableDictionary *)paramsDictionary{
    if(!_paramsDictionary){
        _paramsDictionary = [[NSMutableDictionary alloc] init];
    }
    return _paramsDictionary;
}
@end
